import { DatePicker } from 'antd';
import moment, { Moment } from 'moment';
import { useEffect, useState } from 'react';
import { RangePickerProps } from 'antd/lib/date-picker/generatePicker';

const { RangePicker } = DatePicker;

export default function RangePickerWidget(props: RangePickerProps<string>) {
  const { value, onChange, ...res } = props;
  const [val, setVal] = useState<[Moment, Moment]>();

  useEffect(() => {
    if (value) {
      setVal([moment(value[0]), moment(value[1])]);
    }
  }, [value]);

  function handleChange(
    value: [Moment, Moment],
    valueString: [string, string],
  ) {
    const format = res.format as string;
    onChange?.([value[0].format(format), value[1].format(format)], valueString);
  }

  // @ts-ignore
  return <RangePicker {...res} value={val} onChange={handleChange} />;
}
